package mc.support.taobao.api.comm;

import com.alibaba.fastjson.JSONObject;
import com.taobao.api.ApiException;
import com.taobao.api.TaobaoClient;
import com.taobao.api.TaobaoRequest;
import com.taobao.api.TaobaoResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created with IntelliJ IDEA. <br/>
 * Author: Francis Yuen    <br/>
 * Date: 2014-11-10  <br/>
 */
public class TaobaoClientWrapper implements TaobaoClient {

    private final static Logger logger = LoggerFactory.getLogger( "ming-apis" );

    private final TaobaoClient target;

    public TaobaoClientWrapper( TaobaoClient target ) {
        this.target = target;
    }

    @Override
    public <T extends TaobaoResponse> T execute( TaobaoRequest<T> request ) throws ApiException {
        return execute( request, null );
    }

    @Override
    public <T extends TaobaoResponse> T execute( TaobaoRequest<T> request, String session ) throws ApiException {
        long st = System.currentTimeMillis();
        T result = null;
        Throwable t = null;
        try {
            result = target.execute( request, session );
        } catch ( Throwable e ) {
            t = e.getCause() == null ? e : e.getCause();
            if ( t instanceof ApiException ) {
                throw (ApiException) t;
            } else {
                throw new RuntimeException( "unexpected exception when calling taobao client. ", t );
            }
        } finally {
            st = System.currentTimeMillis() - st;
            String yn = t == null ? "Y" : "N",
                    expMsg = t == null ? "-" : t.getMessage(),
                    reqTextParams = "-", respErrorCode = "-", respMsg = "-", respSubCode = "-", respSubMsg = "-";

            if ( result != null ) {
                respErrorCode = result.getErrorCode() == null ? respErrorCode : result.getErrorCode();
                respMsg = StringUtils.isEmpty( result.getMsg() ) ? respMsg : result.getMsg();
                respSubCode = result.getSubCode() == null ? respSubCode : result.getSubCode();
                respSubMsg = StringUtils.isEmpty( result.getSubMsg() ) ? respMsg : result.getSubMsg();
                yn = result.isSuccess() ? yn : "N";
            }
            reqTextParams = "N".equals( yn ) ? JSONObject.toJSONString( request.getTextParams() ) : reqTextParams;

            try {
                logger.info( "[({},{},{}ms)({},{})({},{},{},{})({})]",
                        request.getApiMethodName(), yn, st, session, reqTextParams,
                        respErrorCode, respMsg, respSubCode, respSubMsg, expMsg );
            } catch ( Exception ignored ) {
            }
        }
        return result;
    }

}
